package com.learn.mvc.config;

import com.learn.mvc.handler.LoginInterceptor;
import com.learn.mvc.handler.MyFilter;
import com.learn.mvc.handler.MyServlet;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    // 添加拦截器对象，注入到容器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 使用自定义的拦截器对象
        LoginInterceptor loginInterceptor = new LoginInterceptor();
        // 拦截的请求地址
        String path[] = {"/user/**"};
        // 不拦截的地址
        String excludePath [] = {"/user/login"};
        registry.addInterceptor(loginInterceptor)
                .addPathPatterns(path)
                .excludePathPatterns(excludePath);
    }

    // 定义方法，注册自定义的servlet
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
        // public ServletRegistrationBean(T servlet, String... urlMappings)
        // 第一个参数是 servlet对象，第二个是url地址
        //ServletRegistrationBean bean = new ServletRegistrationBean(new MyServlet(), "/myservlet");

        //第二种不传递参数 创建servlet
        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet(new MyServlet());
        bean.addUrlMappings("/myservlet", "/testservlet");
        return  bean;
    }

    // 定义方法，注册自定义的filter
    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        filterRegistrationBean.setFilter(new MyFilter());
        filterRegistrationBean.addUrlPatterns("/user/*");
        return filterRegistrationBean;
    }
}
